charset='utf-8'

var flag = false;//标记，用来按条件加载js的（渲染）
//---------获取项目名称----------------------------------
var projectName = getProjectName();
//---------初始获取购物车列表-------------------------
getCartList();

//---------初始获取购物车列表  start-----------------------------------------------
function getCartList() {
    $.ajax({
        url:projectName+"/CartListServlet",
        dataType:'json',
        async:false,
        success:function (result) {
            //console.log("获取购物车列表::"+result);
            dealWithData(result);
            flag = true;//购物车已经加载完成，标记设置为true，代表可以去加载负责渲染的js文件了
        },
        error:function () {
            console.log("sth wrong..")
        }
    });
}
//---------初始获取购物车列表  end--------------------------------------------


//---------------------------处理购物车列表 start-------------------------------------------
function dealWithData(result) {
    var cartDiv = $(".checkout-items");
    cartDiv.empty();
    var str = '';
    $.each(result.data,function (index,item) {
        //购物车商品html
        str += '<div class="card ecommerce-card">\n' +
            '                                    <div class="card-content">\n' +
            '                                        <div class="item-img text-center">\n' +
            '                                            <img src="../../../'+item.imgUrl+'" alt="img-placeholder">\n' +
            '                                        </div>\n' +
            '                                        <div class="card-body">\n' +
            '                                            <div class="item-name">\n' +
            '                                                <span>'+item.goodsName+'</span>\n' +
            '                                                <p class="item-company">By <span class="company-name">Amazon</span></p>\n' +
            '                                                <p class="stock-status-in">In Stock</p>\n' +
            '                                            </div>\n' +
            '                                            <div class="item-quantity">\n' +
            '                                                <p class="quantity-title">Quantity</p>\n' +
            '                                                <div class="input-group quantity-counter-wrapper">\n' +
            '                                                    <input type="text" class="quantity-counter" value="'+item.amount+'">\n' +
            '                                                </div>\n' +
            '                                                <input type="hidden" class="item_stock" value="'+item.stock+'">\n' +
            '                                                <input type="hidden" class="item_cartId" value="'+item.cartId+'">\n' +
            '                                                <input type="hidden" class="item_oldAmount" value="'+item.amount+'">\n' +
            '                                            </div>\n' +
            '                                            <p class="delivery-date">Delivery by, Wed Apr 25</p>\n' +
            '                                            <p class="offers">17% off 4 offers Available</p>\n' +
            '                                        </div>\n' +
            '                                        <div class="item-options text-center">\n' +
            '                                            <div class="item-wrapper">\n' +
            '                                                <div class="item-rating">\n' +
            '                                                    <div class="badge badge-primary badge-md">\n' +
            '                                                        4 <i class="feather icon-star ml-25"></i>\n' +
            '                                                    </div>\n' +
            '                                                </div>\n' +
            '                                                <div class="item-cost">\n' +
            '                                                    <h6 class="item-price">\n' +
            '                                                        '+item.unitPrice+'\n' +
            '                                                    </h6>\n' +
            '                                                    <p class="shipping">\n' +
            '                                                        <i class="feather icon-shopping-cart"></i> Free Shipping\n' +
            '                                                    </p>\n' +
            '                                                </div>\n' +
            '                                            </div>\n' +
            '                                            <div class="wishlist remove-wishlist">\n' +
            '                                                <i class="feather icon-x align-middle"></i> Remove\n' +
            '                                            </div>\n' +
            '                                            <div class="cart remove-wishlist">\n' +
            '                                                <i class="fa fa-heart-o mr-25"></i> Wishlist\n' +
            '                                            </div>\n' +
            '                                        </div>\n' +
            '                                    </div>\n' +
            '                                </div>';
    });//console.log(str)
    cartDiv.html(str);

    //设置购物车总金额
    setTotalPrice();

}
//---------------------------处理购物车列表 end---------------------------------------------


//------------------------------修改购物车总金额 start---------------------------------------
function setTotalPrice() {
    var sum = 0;
    //循环购物车中的所有商品
    $.each($(".ecommerce-card"),function (index,item) {
        //商品价格
        var unitPrice = $(this).find(".item-price").text();//console.log("unitPrice::"+unitPrice)
        //商品数量
        var amount = $(this).find(".quantity-counter").val();//console.log("amount::"+amount)
        //求和（为避免精度问题，先乘１００再除１００）
        sum += unitPrice*100*amount;
    })
    //在前端显示
    console.log("aaa:::"+sum+","+sum/100);
    $(".detail-amt.total-amt").text("$"+(sum/100).toFixed(2));//这个还是加了一下fix是因为4.52*100都会失精度，恶心吧。
}
//------------------------------修改购物车总金额 end---------------------------------------

//乘法

function multiNum (a,b){
    var c = 0,
        d = a.toString(),
        e = b.toString();
    try {
        c += d.split(".")[1].length;
    } catch (f) { }
    try {
        c += e.split(".")[1].length;
    } catch (f) { }
    return Number(d.replace(".","")) * Number(e.replace(".","")) / Math.pow(10,c);
}
//加法

function addNum (a,b){

    var c,d,e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
     e = Math.pow(10,Math.max(c,d)),(multiNum(a,e) + multiNum(b,e)) / e;
    return e.toLocaleString().replace(/[,]/g, '');
}

//---------------------------获取项目名称 start---------------------------------------------
function getProjectName() {
    //获取路径
    var pathName = location.pathname;console.log("pathName"+pathName)
    //截取，得到项目名称
    var projectName = pathName.substring(0,pathName.substr(1).indexOf("/")+1);
    return projectName;
}
//---------------------------获取项目名称 end---------------------------------------------

$(function () {
    $("#aaaa").click(function () {
        alert(999);
    })
    //---------------------------删除购物车中商口按钮的动态绑定事件 start------------------------
    $("body").on("click",".wishlist.remove-wishlist",function () {//注意点，这个别写错了，先是click，而且中间的选择器不写$()
        //去后台删除购物车中该商品的记录
        var cartId = $(this).parents(".card.ecommerce-card").find(".item_cartId").val();console.log("item_cartId::"+cartId);
        delCart(cartId);
        //删除它所在的购物车
        $(this).parents(".card.ecommerce-card").remove();
        //修改购物车总金额
        setTotalPrice();
    });
    //---------------------------删除购物车中商口按钮的动态绑定事件 end------------------------

    //---------------------------提交订单　start-----下面这段代码写在这里不生效，需要写在shop.js中，不知道为什么-------------------
    //console.log("dddddddddd::"+$(".btn-cvv").length)
    // $(".btn-cvv").click(function () {
    //      console.log("ddd")
    //      if ($(".input-cvv").val().length == 3) {
    //          //需要传的数据有：cartIds
    //          var cartIds = [];
    //          $(".item_cartId").each(function (index,item) {
    //              cartIds.push(item.val());
    //          });
    //          console.log(cartIds)
    //          // $.ajax({
    //          //     url:projectName+"/OrderAddServlet",
    //          //     data:{cartIds:cartIds},
    //          //     success:function (result) {
    //          //         console.log(result);
    //          //     }
    //          // })
    //          toastr.success('Success', 'Payment received Successfully', { "positionClass": "toast-bottom-right" });
    //      } else {
    //          toastr.warning('Error', 'Please Enter Valid Details', { "positionClass": "toast-bottom-right" });
    //      }
    //
    //  });
    //---------------------------提交订单　end------------------------
})

//---------------------------定时循环判断购物车列表是否加载完成 start------------------------
var t = setInterval(function () {
    if(flag){
        // jQuery.getScript("../../../app-assets/vendors/js/vendors.min.js");
        jQuery.getScript("../../../app-assets/vendors/js/forms/spinner/jquery.bootstrap-touchspin.js");
        //jQuery.getScript("../../../app-assets/js/scripts/pages/app-ecommerce-shop.js");
        jQuery.getScript("../../../app-assets/js/scripts/pages/app-ecommerce-checkout-touchSpin.js");

        // jQuery.getScript("../../../app-assets/vendors/js/extensions/jquery.steps.min.js");
        // jQuery.getScript("../../../app-assets/vendors/js/forms/validation/jquery.validate.min.js");
        // jQuery.getScript("../../../app-assets/vendors/js/extensions/toastr.min.js");

        // jQuery.getScript("../../../app-assets/js/core/app-menu.js");
        // jQuery.getScript("../../../app-assets/js/core/app.js");
        // jQuery.getScript("../../../app-assets/js/scripts/components.js");
        //touchSpin();
        clearInterval(t);
    }
},50);
//---------------------------定时循环判断购物车列表是否加载完成 end-------------------------





//---------------------------删除购物车中商品 start------------------------
function delCart(cartId) {
    $.ajax({
        url:projectName+"/CartDelServlet",
        data:{cartId:cartId},
        success:function (result) {
            console.log("remove goods:"+result);
        }
    })
}
//---------------------------删除购物车中商品 end------------------------